package com.whl.sm.controller.approval;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whl.sm.common.result.Result;
import com.whl.sm.common.util.UploadUtils;
import com.whl.sm.controller.BaseController;
import com.whl.sm.dto.SelectDto;
import com.whl.sm.dto.SelectIntDto;
import com.whl.sm.model.approval.VApproval;
import com.whl.sm.model.notice.Attachment;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.model.system.Role;
import com.whl.sm.service.approval.VApprovalService;
import com.whl.sm.service.notice.AttachmentService;
import com.whl.sm.service.repair.DataOperateLogService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.service.system.RoleService;
import com.whl.sm.sysEnum.CommonEnum;
import com.whl.sm.vo.ApprovalRoleVo;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2022-01-12
 */
@Slf4j
@RestController
@RequestMapping("/v-approval")
public class VApprovalController extends BaseController {

    @Value("${ROOT_PATH}")
    private String rootPath;

    @Autowired
    private VApprovalService vApprovalService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DataOperateLogService dataOperateLogService;

    @Autowired
    private AttachmentService attachmentService;


    @RequestMapping("/apRoleList")
    public Result apRoleList(HttpServletRequest request){
        Page<Object> resultPage = new Page<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        String likeName = request.getParameter("likeName");
        if (!likeName.equals("undefined") && !likeName.equals("")){
            List<OrgUserInfo> applicants = orgUserInfoService.list(new QueryWrapper<OrgUserInfo>().like("user_name",likeName));
            if (applicants.size()>0){
                queryWrapper.in("applicant",applicants.stream().map(OrgUserInfo::getUserId));
            }else {
                return Result.ok(resultPage);
            }
        }
        setHttpRequestQueryWrapper(queryWrapper,"approval_remark","data_id","approval_status");
        queryWrapper.eq("data_type","ROLE_APPROVAL");
        queryWrapper.ne("is_del",1);
        queryWrapper.orderByDesc("update_time");
        resultPage = vApprovalService.page(getPage(),queryWrapper);
        List<Object> rtList = resultPage.getRecords().stream().map(obj->{
            VApproval item = (VApproval)obj;
            Role apRole = roleService.getById(item.getDataId());
            OrgUserInfo applicant = orgUserInfoService.getByUserId(item.getApplicant());
            OrgUserInfo operator = orgUserInfoService.getByUserId(item.getOperator());
            ApprovalRoleVo rtValue =  new ApprovalRoleVo(item,apRole,applicant,operator);
            List<Attachment> linkFile = attachmentService.getByDataId(item.getId());
            if (linkFile.size()>0){
                rtValue.setFileList(
                        linkFile.stream().map(Attachment::getFile).collect(Collectors.toList())
                );
            }
            return rtValue;
        }).collect(Collectors.toList());
        resultPage.setRecords(rtList);
        return Result.ok(resultPage);
    }

    @RequestMapping("/submitRoleAp")
    public Result uploadApproval(@RequestParam MultipartFile apImg , @RequestParam("dataId") String dataId,
                                 @RequestParam("dataType") String dataType,
                                 @RequestParam("approvalRemark") String approvalRemark,
                                 HttpServletRequest request){
        String path = "/approval/apImg";
        try{
            //新增审核信息
            VApproval apData = new VApproval();
            apData.setDataId(dataId); apData.setDataType(dataType); apData.setApprovalRemark(approvalRemark);
            Result insertRt  = vApprovalService.update(apData);
            if (!insertRt.isOk()){
                return insertRt;
            }
            Result addLog = dataOperateLogService.addOperateLog(apData.getId(),"ROLE_APPROVAL","提交申请");
            if (!addLog.isOk()){
                return addLog;
            }
            List<Map<String,Object>> fileList = UploadUtils.saveFile(request,path,this.rootPath,"apImg");
            String resultPath = "";
            if (fileList.size()>0){
                for (Map<String,Object> item :fileList){
                    Attachment attachment = new Attachment();
                    attachment.setDataId(apData.getId());
                    attachment.setDataType(dataType);
                    attachment.setFile(String.valueOf(item.get("filePath")));
                    attachment.setFileSize(Integer.valueOf(item.get("fileSize")+""));
                    attachment.setFileName(String.valueOf(item.get("originalName")));
                    attachment.setFileType(String.valueOf(item.get("mimeType")));
                    attachmentService.update(attachment);
                }
            }
            System.out.println(resultPath);
        }catch (Exception e){
            log.error("认证图片上传失败----->"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }



    @RequestMapping("/getByCurrent")
    public Result getByCurrentUser(@RequestParam("dataType") String dataTpe){
        VApproval resultData = null;
        if (dataTpe.equals("ROLE_APPROVAL")){
            resultData = vApprovalService.getByUserOfRole(dataTpe);
        }else {
            resultData = vApprovalService.getByUserId(dataTpe);
        }
        return Result.ok(resultData);
    }


    @RequestMapping("/auditStatus")
    public Result auditStatus(@RequestBody ApprovalRoleVo approvalRoleVo){
        return Result.ok();
    }

    @RequestMapping("/status")
    public Result approvalStatus() {
        List<SelectIntDto> rtList = new ArrayList<>();
        for (CommonEnum.ApprovalStatus item:CommonEnum.ApprovalStatus.values()) {
            SelectIntDto insert =  new SelectIntDto(item.getStep(),item.getValue(),null,false);
            rtList.add(insert);
        }
        return Result.ok(rtList);
    }

}
